package trace

import (
	"math/rand"
	"sync/atomic"
	"time"
)

const (
	slotLength = 2048
)

var ignoreds = []string{"/metrics", "/monitor/ping"}

func init() {
	rand.Seed(time.Now().UnixNano())
}

type probabilitySampler struct {
	probability float64
	slot        [slotLength]int64
}

// newSampler new probability sampler
func newProbabilisticSampler(probability float64) sampler {
	if probability < 0 {
		probability = 0
	}
	if probability > 1 {
		probability = 1
	}
	return &probabilitySampler{probability: probability}
}

func random(probability float64, operationName string) (bool, float64) {
	for _, ignored := range ignoreds {
		if operationName == ignored {
			return false, 0
		}
	}
	return rand.Float64() < probability, probability
}

func (p *probabilitySampler) IsSampled(traceID uint64, operationName string) (bool, float64) {
	if p.probability == 0 {
		return false, 0
	}
	for _, ignored := range ignoreds {
		if operationName == ignored {
			return false, 0
		}
	}
	if p.probability == 1 {
		return true, 1
	}
	now := time.Now().Unix()
	idx := oneAtTimeHash(operationName) % slotLength
	old := atomic.LoadInt64(&p.slot[idx])
	if old != now {
		atomic.SwapInt64(&p.slot[idx], now)
		return true, 1
	}
	return rand.Float64() < p.probability, p.probability
}

func (p *probabilitySampler) Close() error {
	return nil
}

func oneAtTimeHash(s string) (hash uint32) {
	b := []byte(s)
	for i := range b {
		hash += uint32(b[i])
		hash += hash << 10
		hash ^= hash >> 6
	}
	hash += hash << 3
	hash ^= hash >> 11
	hash += hash << 15
	return
}
